package com.songxh.core.page;

import com.songxh.core.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * pageData工具类
 * @author songxh
 * @create 2022-12-19-17:23
 */
@Slf4j
public class PageDataGenerator {
    /**
     * 排序字段
     */
    public final static String SORT_STRING = "sort";
    /**
     * 升序降序
     */
    public final static String ORDER_STRING = "order";
    /**
     * 结束日期
     */
    public final static String END_DATE = "endDate";
    /**
     * 第几页
     */
    public final static String PAGE_STRING = "page";
    /**
     * 每页数量
     */
    public static final String PAGESIZE_STRING = "pageSize";
    /**
     * 是否分页
     */
    public static final String ISPAGE_STRING = "isPage";

    /**
     * 生成PageData对象
     *
     * @param request
     * @param isPage  是否分页
     * @return
     */
    public static PageData newInstall(HttpServletRequest request, boolean isPage, PageData pageData) {
        if (pageData == null) {
            pageData = new PageData();
        }
        initParama(pageData, request, isPage);
        initOrder(pageData, request);
        return pageData;
    }

    /**
     * 初始化排序信息
     *
     * @param pageData
     * @param request
     */
    private static void initOrder(PageData pageData, HttpServletRequest request) {
        String sort = request.getParameter(SORT_STRING);
        String order = request.getParameter(ORDER_STRING);
        if (StringUtils.isNotBlank(sort)) {
            try {
                String sortSql = sort + " " + order;
                sortSql = SqlUtils.escapeOrderBySql(sortSql);
                pageData.setOrderBy(sortSql);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
    }

    /**
     * 初始化参数信息
     *
     * @param pageData
     * @param request
     * @param isPage
     */
    private static void initParama(PageData pageData, HttpServletRequest request, boolean isPage) {
        Map<String, Object> params = pageData.getParams();
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            if (StringUtils.equalsAny(name, PAGE_STRING, PAGESIZE_STRING)) {
                continue;
            }
            String value = request.getParameter(name);
            if (StringUtils.isNotEmpty(value)) {
                value = value.trim().replace("\\", "\\\\%").replace("%", "\\%");
                params.put(name, value);
            }
        }
        params.remove(PAGE_STRING);
        params.remove(PAGESIZE_STRING);
        pageData.setIsPage(isPage);
    }
}
